package com.tpix;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.tpix.photo.Photo;
import com.tpix.photo.PhotoDAO;

public class SaveServlet extends HttpServlet {
	
	private static final long serialVersionUID = -2869288637953828242L;
	private PhotoDAO dao = new PhotoDAO();
	
	@Override
	protected void doPost(HttpServletRequest request,HttpServletResponse response)
		throws IOException,ServletException{
		
		//get the information from the request
		String title = request.getParameter("title");
		String caption = request.getParameter("caption");
		String albumName = request.getParameter("album");
		String description = request.getParameter("description");
		String newAlbumName = request.getParameter("newalbum");
		String location = request.getParameter("location");
		String tags = request.getParameter("tags");
		String blobKey = request.getParameter("blob-key");
		
		// get reference to core object
		PixieCore core = (PixieCore)request.getSession().getAttribute("core");
		if (core == null) {
			core = new PixieCore();
		}
		
		//create the date now
		Date date = new Date();
		
		// Create new photo object
		Photo photo = new Photo(title,caption,blobKey);
		
		// set to newalbum if New Album was selected
		if(albumName.equals("New Album")){
			albumName = newAlbumName;
		}
		// set album to Default if input is blank
		if(albumName.equals("")){
			//set the albumName to default
			albumName = "Default";
			photo.setAlbumName(albumName);
		}else{
			photo.setAlbumName(albumName);
		}
	
		// put other information in photo
		photo.setDate(date);
		photo.setTagList(tags);
		photo.setLocation(location);
		photo.setDescription(description);
		photo.setUser(core.getUserName());
		
		//save the photo
		dao.save(photo);
		
		// update album in core moved from line 38
		//to here after the manipulation of albumName
		core.setAlbum(albumName);
		//now only set the core in the session once
		request.getSession().setAttribute("core", core);
		
		//What is the photo id, now that it is saved?
		System.out.println("The id for this photo is "+photo.getId());
		System.out.println("Title: "+dao.findById(photo.getId()).getTitle());
		System.out.println("Caption: "+dao.findById(photo.getId()).getCaption());
		System.out.println("Album Name: "+dao.findById(photo.getId()).getAlbumName());
				
		response.sendRedirect("/home.jsp");
	}
	
	
}
